package com.xiaouyudeguang.common.resource;

import com.xiaouyudeguang.common.manager.WebSocketSessionManager;
import com.xiaouyudeguang.common.model.WebSocketMessage;
import com.xiaouyudeguang.common.respose.ResultDto;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/websocket")
public class WebSocketResource {

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ResultDto<Boolean> sendMessage(@RequestBody WebSocketMessage message) throws IOException {
        WebSocketSession session = WebSocketSessionManager.SESSION_POOL.get(message.getUserId());
        if (session != null) {
            session.sendMessage(new TextMessage(message.getMessage()));
        }
        return ResultDto.ok();
    }

    @RequestMapping(value = "/sendBatch", method = RequestMethod.POST)
    public ResultDto<Boolean> sendMessage(@RequestBody List<WebSocketMessage> messageList) throws IOException {
        for (WebSocketMessage message : messageList) {
            WebSocketSession session = WebSocketSessionManager.SESSION_POOL.get(message.getUserId());
            if (session != null) {
                session.sendMessage(new TextMessage(message.getMessage()));
            }
        }
        return ResultDto.ok();
    }
}
